package fightplan.algorithmen.ko;

import java.awt.Component;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import fightplan.algorithmen.Layout;
import fightplan.business.Fight;
import fightplan.business.FightEntry;
import fightplan.business.FighterHolder;

public class KOLayout implements Layout {

	private List<KOPanel> panels;
	private Map<Fight, Integer> fightLocation;
	private KOPanel endSheet;
	private FinalrundePanel finalrundeSheet;

	KOLayout() {
		panels = new ArrayList<KOPanel>();
		fightLocation = new HashMap<Fight, Integer>();
	}

	public Component getSheetComponent(int index) {
		return panels.get(index);
	}

	public int getSheetCount() {
		return panels.size();
	}

	/**
	 * Weisst rekursiv alle Fights einem Panel zu.
	 * 
	 * @param fight
	 *            Die root, von welcher alle angehängten Kämpfe dem Panel
	 *            zugeordnet werden.
	 * @param panel
	 *            Das Panel, auf dem sich dieser Kampf befindet
	 */
	void setFightLocation(Fight fight, KOPanel panel) {
		if (!fightLocation.containsKey(fight)) {
			fightLocation.put(fight, panels.indexOf(panel));
		}
		for (FightEntry fightEntry : fight.getFightEntries()) {
			if (fightEntry.getFighterProvider() instanceof FighterHolder) {
				setFightLocation(((FighterHolder) fightEntry.getFighterProvider()).getFight(), panel);
			}
		}
	}

	void setFightLocation(List<Fight> fights, KOPanel panel) {
		if (fights == null)
			return; // Kann bei "Nicht-Trostrunde" vorkommen
		int index = panels.indexOf(panel);
		for (Fight fight : fights) {
			fightLocation.put(fight, index);
		}
	}

	public int getSheetIndexForFight(Fight fight) {
		if (fightLocation.containsKey(fight)) {
			return fightLocation.get(fight);
		} else {
			return -1;
		}
	}

	List<KOPanel> getPanels() {
		return panels;
	}

	// unserialisable

	private void writeObject(ObjectOutputStream out) throws IOException {
		throw new IllegalStateException("Should not be called");
	}

	private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
		throw new IllegalStateException("Should not be called");
	}

	public KOPanel getEndSheet() {
		return endSheet;
	}

	public void setEndSheet(KOPanel endSheet) {
		this.endSheet = endSheet;
	}

	public FinalrundePanel getFinalrundeSheet() {
		return finalrundeSheet;
	}

	public void setFinalrundeSheet(FinalrundePanel finalrundeSheet) {
		this.finalrundeSheet = finalrundeSheet;
	}

}